﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Design;
using Needle.DevToolkit.Traits;
using System.Reflection;
using System.Linq.Expressions;

namespace Needle.DevToolkit.Services.UI
{

    public class ItemVerb : DesignerVerb
    {
        private Action<ItemVerb, IItem> _handler;
        private Type _trait;

        public ItemVerb(string text, Action<ItemVerb, IItem> handler, CommandID id, Type trait)
            : base(text, null, id)
        {
            _handler = handler;
            _trait = trait;
        }

        public override void Invoke()
        {
            Invoke(null);
        }

        public override void Invoke(object arg)
        {
            if (this._handler != null)
            {
                try
                {
                    this._handler(this, arg as IItem);
                }
                catch (CheckoutException exception)
                {
                    if (exception != CheckoutException.Canceled)
                    {
                        throw;
                    }
                }
            }
        }

        public virtual bool CanOperateOn(object item)
        {
            if (_trait != null)
            {
                return item == null ? false : _trait.IsAssignableFrom(item.GetType());
            }
            return true;
        }
    }
}
